package util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Properties;

import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class WeixinUtil {
		
		public static String QRCodePath = "Upload/QRCode";
		
		public static String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
		
		public static String getQRCodeUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
		
		public static String getImgUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode";
		
		public static String getWeChatInfoUrl="https://api.weixin.qq.com/cgi-bin/user/info";
		
		public static String getJsApiTicket="https://api.weixin.qq.com/cgi-bin/ticket/getticket";
		
		public static String getSendMsgUrl="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";
		
		public static String getUnionIdUrl="https://api.weixin.qq.com/cgi-bin/user/info?access_token=";
		
		//获取Access_token
		public static String getAccessToken(){
			String bodyParams = "grant_type=client_credential&appid="+ConfigUtil.WECHAT_PUBLIC_APPID+"&secret="+ConfigUtil.WECHAT_PUBLIC_SECRET;
			JSONObject obj =JSON.parseObject(HttpRequest(getAccessTokenUrl,HttpMethod.GET,"",bodyParams)); 
			return obj.get("access_token").toString();
		}
		//获取获取用户基本信息 (准备返回昵称)
		public static String getWeChatInfo(String access_token,String open_id){
			/*请求返回参数列子
			 * {
				   "subscribe": 1, 
				   "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M", 
				   "nickname": "Band", 
				   "sex": 1, 
				   "language": "zh_CN", 
				   "city": "广州", 
				   "province": "广东", 
				   "country": "中国", 
				   "headimgurl":  "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4
				eMsv84eavHiaiceqxibJxCfHe/0",
				  "subscribe_time": 1382694957,
				  "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
				  "remark": "",
				  "groupid": 0,
				  "tagid_list":[128,2]
				}*/
			String bodyParams = "access_token="+access_token+"&openid="+open_id+"&lang=zh_CN";
			JSONObject obj =JSON.parseObject(HttpRequest(getWeChatInfoUrl,HttpMethod.GET,"",bodyParams));
			if(obj.get("errcode")!=null){
				return "nickname_err";
			}
			return obj.get("nickname").toString();
		}
		//生成临时二维码ticket
		public static String getTempQRCode(String access_token,String member_id){
			
			JSONObject param2 = new JSONObject();
			param2.put("scene_id", member_id);
			
			JSONObject param1 = new JSONObject();
			param1.put("scene", param2);
			
			JSONObject param = new JSONObject();
			param.put("expire_seconds", "604800");
			param.put("action_name", "QR_SCENE");
			param.put("action_info", param1);
			
			//例如 {"expire_seconds": 604800, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "test"}}}
			
			JSONObject retJson = JSON.parseObject(HttpRequest(getQRCodeUrl+access_token, HttpMethod.POST, "", param.toJSONString()));
			
			if(retJson.get("errcode")!=null){
					  return "errcode";
			}
			return retJson.get("ticket").toString();
		}
		//获取二维码图片并上传到阿里云
		public static String getQRCodeImg(String ticket) throws Exception{
			String fileName = HttpRequestFile(getImgUrl, HttpMethod.GET, "", "ticket="+java.net.URLEncoder.encode(ticket,"utf-8"));
			return fileName;
		}
		//拿ticket获取文件流  生成名字并上传到阿里云   获取文件
		public static String HttpRequestFile(String path, HttpMethod method, String headerParams, String bodyParams) {
			InputStream is = null;
			String fileName = "";
			try {
				URI uri = new URI(path);
				SimpleClientHttpRequestFactory schr = new SimpleClientHttpRequestFactory();
				
				if (bodyParams != null && !"".equals(bodyParams) && HttpMethod.GET.equals(method)) {
					uri = new URI(uri.toString()+"?"+bodyParams);
				}
				
				ClientHttpRequest chr = schr.createRequest(uri, method);

				HttpHeaders headers = chr.getHeaders();
				if (headerParams != null && !"".equals(headerParams)) {
					System.out.println(headerParams);
					String[] pList = headerParams.split("&");
					for (String p : pList) {
						String[] entry = p.split("=");
						headers.set(entry[0], entry[1]);
					}
				}
				
				if (bodyParams != null && !"".equals(bodyParams) && HttpMethod.POST.equals(method)) {
					chr.getBody().write(bodyParams.getBytes());// body中设置请求参数
				}
				ClientHttpResponse res = chr.execute();
				is = res.getBody();
				ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); 
				byte[] buff = new byte[100]; //buff用于存放循环读取的临时数据 
				int rc = 0; 
				while ((rc = is.read(buff, 0, 100)) > 0) { 
				swapStream.write(buff, 0, rc); 
				} 
				byte[] fileByte = swapStream.toByteArray();
				fileName = OssUtil.UploadQRImg(QRCodePath,fileByte);
			} catch (URISyntaxException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return fileName;
		}
		
		public static String HttpRequest(String path, HttpMethod method, String headerParams, String bodyParams) {
			String re = "";
			try {
				URI uri = new URI(path);
				SimpleClientHttpRequestFactory schr = new SimpleClientHttpRequestFactory();
				
				if (bodyParams != null && !"".equals(bodyParams) && HttpMethod.GET.equals(method)) {
					uri = new URI(uri.toString()+"?"+bodyParams);
				}
				
				ClientHttpRequest chr = schr.createRequest(uri, method);

				HttpHeaders headers = chr.getHeaders();
				if (headerParams != null && !"".equals(headerParams)) {
					System.out.println(headerParams);
					String[] pList = headerParams.split("&");
					for (String p : pList) {
						String[] entry = p.split("=");
						headers.set(entry[0], entry[1]);
					}
				}
				
				if (bodyParams != null && !"".equals(bodyParams) && HttpMethod.POST.equals(method)) {
					chr.getBody().write(bodyParams.getBytes());// body中设置请求参数
				}
				ClientHttpResponse res = chr.execute();
				InputStream is = res.getBody(); // 获得返回数据,注意这里是个流
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				String str = "";
				while ((str = br.readLine()) != null) {
					re += str;
				}
			//	System.out.println(re);// 获得页面内容或返回内容
			} catch (URISyntaxException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return re;
		}
		public static void main(String[] args) {
			String token = getAccessToken();
			String ticket = getTempQRCode(token,"");
			System.out.println(token);
			System.out.println(ticket);
			try {
				String filePah = getQRCodeImg(ticket);
				System.out.println(filePah);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
			java.util.Date date=new java.util.Date();  
			String now=sdf.format(date); 
			System.out.println(now);
			JSONObject obj = new JSONObject();
			obj.put("token", token);
			obj.put("time", now);
			System.out.println(obj.toJSONString());
		}
	
		//菜单生成json 直接在网页上用微信公众平台接口调试工具 来生成
		public static void caidan(){
/*			
 {
			    "button": [
			        {
			            "name": "了解友米", 
			            "sub_button": [
			                {
								"type": "media_id",
								"name": "赚米项目",
								"media_id": "_JRoIVTJ6412fKobOIiENiI0YjpYgL3_gtLhrXPi7_o"
			                }, 
			                {
			                    "type": "view", 
			                    "name": "赚米资讯", 
			                    "url": "http://wap.uniplaza.com/index/noticeList.do?page_index=1"
			                }, 
			                {
			                    "type": "view", 
			                    "name": "赚米学院", 
			                    "url": "http://rest-java-mall.uniposts.com/v2/page/adPage?ad_id=285"
			                }
			            ]
			        }, 
			        {
			            "type": "view", 
			            "name": "友米商城", 
			            "url": "http://wechat-java-mall.uniposts.com/login/register.do"
			        }, 
			        {
			            "name": "联系友米", 
			            "sub_button": [
			                 {
								"type": "click",
								"name": "友米客服",
								"key":"V1001_Service"
			                }, 
			                {
			                    "type": "click",
								"name": "加入友米",
								"key":"V1002_Join"
			                }, 
			                {
			                     "type": "view", 
								 "name": "App下载", 
			                     "url": "http://a.app.qq.com/o/simple.jsp?pkgname=com.uniplaza.fenx"
			                }
			            ]
			        }
			    ]
			}
		*/
			//运维菜单
		/*	
			
			{
			    "button": [
			        {
			            "name": "戳我", 
			            "sub_button": [
			                {
			                    "type": "view", 
			                    "name": "年货节精选", 
			                    "url": "http://mp.weixin.qq.com/mp/homepage?__biz=MzUyMzEzMDQxNw==&hid=2&sn=484929af4e9ee14cf039cc0f4abda372&scene=18#wechat_redirect"
			                }, 
			                {
			                    "type": "view", 
			                    "name": "友米资讯", 
			                    "url": "http://mp.weixin.qq.com/mp/homepage?__biz=MzUyMzEzMDQxNw==&hid=1&sn=6b95eb11ea0ed3c57abc8c1ffc28a954&scene=18#wechat_redirect"
			                }, 
							{
			                    "type": "view", 
			                    "name": "友米乐微博", 
			                    "url": "https://weibo.com/p/1006065635229027/home"
			                }, 
							{
			                    "type": "view", 
			                    "name": "最新活动", 
			                    "url": "http://mp.weixin.qq.com/mp/homepage?__biz=MzUyMzEzMDQxNw==&hid=3&sn=296b12e9269bfcd7cdfb5707c7140d3b&scene=18#wechat_redirect"
			                }, 
			                {
			                    "type": "view", 
			                    "name": "赚米学院", 
			                    "url": "https://rest.youmikeji.com/v2/page/adPage?ad_id=164"
			                }
			            ]
			        }, 
			        {
			            "type": "view", 
			            "name": "友米商城", 
			            "url": "https://m.uniplaza.com/index"
			        }, 
			        {
			            "name": "会员中心", 
			            "sub_button": [
			                 {
								"type": "click",
								"name": "联系客服",
								"key":"V1001_Service"
			                }, 
							 {
								"type": "media_id",
								"name": "关于友米",
								"media_id": "r_7Pf0Ro0Svq4aPuEsVWoYcVQQjfkoPfRayuK0AfQNU"
			                }, 
			                {
			                    "type": "click",
								"name": "加入友米",
								"key":"V1002_Join"
			                }, 
			                {
			                     "type": "view", 
								 "name": "下载友米", 
			                     "url": "http://a.app.qq.com/o/simple.jsp?pkgname=com.uniplaza.fenx"
			                }, 
							{
								"type": "media_id",
								"name": "常见问题",
								"media_id": "r_7Pf0Ro0Svq4aPuEsVWoSRo6bgCELog0qG1R-j5HYE"
			                }
			            ]
			        }
			    ]
			}
			
			*/
		}
		//获取getJsApiTicket
		public static String getJsApiTicket(String access_token){
			String bodyParams = "access_token="+access_token+"&type=jsapi";
			JSONObject obj =JSON.parseObject(HttpRequest(getJsApiTicket,HttpMethod.GET,"",bodyParams)); 
			if(obj.get("ticket")==null){
				  return "errcode";
		    }else{
		    	return obj.get("ticket").toString();
		    }
			
		}
		
		/*
		 * 推送文本消息
		 *@param openid  
		 *@param content 要发送的内容
		 *@param access_token
		 * */
		
		public static void sendMsgText(String openid,String content,String access_token){
			
			JSONObject  obj = new JSONObject();
			JSONObject  obj1 = new JSONObject();
			
			obj.put("touser",openid);
			obj.put("msgtype","text");
			obj1.put("content", content);
			obj.put("text", obj1);
			JSONObject retJson = JSON.parseObject(HttpRequest(getSendMsgUrl+access_token, HttpMethod.POST, "", obj.toJSONString()));
			
		}
		/*
		 * 推送图片消息
		 *@param openid  
		 *@param content 要发送的内容
		 *@param access_token
		 * */
		
		public static void sendMsgImg(String openid,String media_id,String access_token){
			
			JSONObject  obj = new JSONObject();
			JSONObject  obj1 = new JSONObject();
			
			obj.put("touser",openid);
			obj.put("msgtype","image");
			obj1.put("media_id", media_id);
			obj.put("image",obj1);
			JSONObject retJson = JSON.parseObject(HttpRequest(getSendMsgUrl+access_token, HttpMethod.POST, "", obj.toJSONString()));

		}
		//获取UnionId
		public static String getUnionId(String openid,String access_token){
			
			String a = DeliverUtil.HttpRequest(getUnionIdUrl+access_token+"&openid="+openid, HttpMethod.GET, "", "");
			
			JSONObject msg = JSONObject.parseObject(a);
			if(msg.get("errcode")!=null){
				  return "errcode";
			}
			return msg.get("unionid").toString();
		}
		//获取用户信息
		public static JSONObject getInfo(String openid,String access_token){
			
			String a = DeliverUtil.HttpRequest(getUnionIdUrl+access_token+"&openid="+openid, HttpMethod.GET, "", "");
			
			JSONObject msg = JSONObject.parseObject(a);

			return msg;
		}
		
	    public static  String ID2 = null;
	    public static  String ID3 = null;
	    public static  String ID4 = null;
	    
	    
}
